package com.ikangtai.shecare.personal;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.BaseActivity;
import com.ikangtai.shecare.common.baseView.TopBar;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.ikangtai.shecare.common.util.Validator;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.IOException;

public class FindPasswordActivity extends BaseActivity implements View.OnClickListener {

    private TopBar topBar;
    private EditText phone_edittext;
    private static final int FINDPASSWORD_OK = 1;
    private static final int FINDPASSWORD_NOK = 2;
    private static final int UNREGISTERED = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_personal_find_password);
        EventBus.getDefault().register(this);
        initView();
    }

    private void initView() {
        topBar = (TopBar) findViewById(R.id.topBar);
        topBar.setOnTopBarClickListener(new TopBar.OnTopBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void midLeftClick() {

            }

            @Override
            public void midRightClick() {

            }

            @Override
            public void rightClick() {

            }
        });
        phone_edittext = (EditText) findViewById(R.id.phone_edit);
        findViewById(R.id.nextButton).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.nextButton:
                String phoneOrEmail = phone_edittext.getText().toString().trim();
                if (0 == phoneOrEmail.length()) {
                    Toast.makeText(getApplicationContext(), R.string.mail_phone_not_null, Toast.LENGTH_SHORT).show();
                } else if (!Validator.isEmail(phoneOrEmail) && !Validator.isMobile(phoneOrEmail)) {
                    Toast.makeText(getApplicationContext(), R.string.phone_mail_not_true, Toast.LENGTH_SHORT).show();
                } else if (Validator.isEmail(phoneOrEmail)) {
                    sendByEmail(phoneOrEmail);
                } else if (Validator.isMobile(phoneOrEmail)) {
                    sendByPhone(phoneOrEmail);
                } else {

                }
                break;
        }
    }

    /**
     * 邮件修改密码
     *
     * @param userEmail
     */
    private void sendByEmail(String userEmail) {
        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "login/forgetPasswordForEmail.json?email=" + userEmail;
        okHttpClient.getAsync(appendUrl, okHttpClient.new BaseCallBack() {

            @Override
            public void onFailure(Request request, IOException e) {
                sendNOKResp(FINDPASSWORD_NOK);
                super.onFailure(request, e);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    JSONObject respJSONObj = new JSONObject(response.body().string());
                    int respCode = respJSONObj.getInt("code");
                    if (App.HTTP_RESP_OK == respCode) {
                        sendOKResp(FINDPASSWORD_OK);
                        AppLog.i("find password by email onResponse success!");
                        finish();
                    } else if (App.HTTP_RESP_TOKEN_TIME_OUT == respCode) {
                        unRegistered(UNREGISTERED);
                        AppLog.i("find password by email onResponse respCode failed! is:" + respCode);
                    } else {
                        sendNOKResp(FINDPASSWORD_NOK);
                        AppLog.i("find password by email onResponse respCode failed! is:" + respCode);
                    }
                } catch (JSONException e) {
                    sendNOKResp(FINDPASSWORD_NOK);
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 手机号修改密码，发送验证码
     *
     * @param userPhone
     */
    private void sendByPhone(final String userPhone) {
        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "veri/getCode.json";
        try {
            okHttpClient.add("phoneNumber", userPhone);
            okHttpClient.add("type", 2);
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    sendNOKResp(FINDPASSWORD_NOK);
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");

                        if (App.HTTP_RESP_OK == respCode) {
                            sendOKResp(FINDPASSWORD_OK);
                            Intent nextIntent = new Intent();
                            nextIntent.putExtra("phoneNumber", userPhone);
                            nextIntent.setClass(getApplicationContext(), ResetPasswordActivity.class);
                            startActivity(nextIntent);
                            finish();
                            AppLog.i("find password by phone onResponse success!");
                        } else if (App.HTTP_RESP_TOKEN_TIME_OUT == respCode) {
                            unRegistered(UNREGISTERED);
                            AppLog.i("find password by phone onResponse respCode failed! is:" + respCode);
                        } else {
                            sendNOKResp(FINDPASSWORD_NOK);
                            AppLog.i("find password by phone onResponse respCode failed! is:" + respCode);
                        }
                    } catch (JSONException e) {
                        AppLog.i("find password by phone onResponse failed!");
                        sendNOKResp(FINDPASSWORD_NOK);
                        e.printStackTrace();
                    }
                }
            });
        } catch (JSONException e) {
            sendNOKResp(FINDPASSWORD_NOK);
            e.printStackTrace();
        }
    }

    private void sendNOKResp(int returnCode) {
        EventBus.getDefault().post(Integer.valueOf(returnCode));
    }

    private void sendOKResp(int returnCode) {
        EventBus.getDefault().post(Integer.valueOf(returnCode));
    }

    private void unRegistered(int returnCode) {
        EventBus.getDefault().post(Integer.valueOf(returnCode));
    }

    @Subcriber
    private void handleMyInfo(Integer returnCode) {
        switch (returnCode) {
            case FINDPASSWORD_OK:
                Toast.makeText(getApplicationContext(), getString(R.string.send_success), Toast.LENGTH_SHORT).show();
                break;
            case FINDPASSWORD_NOK:
                //Toast.makeText(getApplicationContext(), "发送失败!", Toast.LENGTH_SHORT).show();
                Toast.makeText(getApplicationContext(), R.string.phone_mail_not_true, Toast.LENGTH_SHORT).show();
                break;
            case UNREGISTERED:
                Toast.makeText(getApplicationContext(), R.string.unregister, Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
